package com.kartoshka.managers {
	import com.kartoshka.interfaces.IValidatable;

	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;

	/**
	 * @author Alexander Zats, 2009
	 */
	public class ValidationManager extends EventDispatcher {
		public static const VALIDATE_STYLE : int = 0x1;
		public static const VALIDATE_CHROME : int = 0x2;
		public static const VALIDATE_INTERNAL_CHILDRENS : int = 0x4;
		public static const VALIDATE_CHILDREN : int = 0x8;
		//TODO this constant should call validateChildrens() in parent UIBase component� lot of questions here.
		public static const VALIDATE_PARENT : int = 0x10;
		public static const VALIDATE_ALL : int = 0x1F;
		private var _queue : Dictionary;

		public function ValidationManager( city : Delhi ) {
			super(this);
			if ( !city ) throw new Error("Singleton error");
			_queue = new Dictionary(true);
		}

		public function addToQueue( instance : IValidatable ) : void {
			if ( !instance ) return;
			if ( !_stage ) throw new Error("You should call ValidationManager.setup( stage ) method first and pass reference to the stage!");
			if ( _queue.hasOwnProperty(instance.uid) ) return;
			trace("\njust added to queu", instance.uid + "\n");
			_queue[ instance.uid ] = instance;
			_stage.invalidate();
			_stage.addEventListener(Event.RENDER, doValidation, false, 0, true);
		}

		private function doValidation(event : Event) : void {
			trace("––––––Validation begin––––––");
			_stage.removeEventListener(Event.RENDER, doValidation, false);
			for each ( var instance : IValidatable in _queue ) {
				trace("\tValidating", instance.uid);
				instance.validate();
				delete _queue[ instance.uid ];
			}
			trace("–––––––Validation end–––––––");
			trace();
		}

		//–––––––––––––––––––––––––––––––––––––––––––––––––––
		//	Static block
		//–––––––––––––––––––––––––––––––––––––––––––––––––––
		private static var _stage : Stage;
		private static var _instance : ValidationManager;

		/*
		 * This method must be called first of all, since class utilize <code>stage.invalidate()</code> method to keep all validation actions in one place.
		 */
		public static function setup( stage : Stage ) : void {
			_stage = stage;
		}

		public static function get instance() : ValidationManager {
			if ( !_instance ) _instance = new ValidationManager(new Delhi());
			return _instance;
		}
	}
}

internal class Delhi {
}